﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FixedLenChain : MonoBehaviour
{
    public float spring = 500f;
    public float drag = 0f;
    public List<float> len;
    public List<Transform> ts;
    public List<Rigidbody> rbs;
    public List<Vector3> pos;
    private void Start()
    {
        GetComponentsInChildren<Rigidbody>(rbs);
        ts = new List<Transform>();
        foreach (var rb in rbs)
        {
            ts.Add(rb.transform);
        }
        len = new List<float>();
        for (int i = 1; i < ts.Count; i++) // e = v-1
        {
            var b = ts[i].position;
            var a = ts[i - 1].position;
            len.Add(Vector3.Distance(a, b));
        }
    }
    void FixedUpdate()
    {
        pos = new List<Vector3>();
        for (int i = 0; i < ts.Count; i++)
        {
            pos.Add(ts[i].position);
        }
        for (int i = 1; i < ts.Count; i++)
        {
            var b = pos[i];
            var a = pos[i - 1];
            var l = b - a;

            rbs[i].MovePosition(a + l.normalized * len[i - 1]);
            //ts[i].position = a + l.normalized * len[i - 1];
            ts[i - 1].up = l.normalized;
        }
    }
}